//
//  QWeiboClient.m
//  huipai_3
//
//  Created by tan xi on 11-9-6.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "QWeiboClient.h"
#import "SBJson.h"

@implementation QWeiboClient

@synthesize delegate, appKey, appSecret, tokenKey, tokenSecret, weiboIndentify;

- (id)initWithAppKey:(NSString*)_appKey 
           appSecret:(NSString*)_appSecret
            tokenKey:(NSString*)_tokenKey
         tokenSecret:(NSString*)_tokenSecret
{
    self = [super init];
    if (self) {
        appKey = _appKey;
        appSecret = _appSecret;
        tokenKey = _tokenKey;
        tokenSecret = _tokenSecret;
    }
    return self;
}

- (void)dealloc
{
    [appKey     release];
    [appSecret  release];
    [tokenKey   release];
    [tokenSecret    release];
    [delegate   release];
    [super      dealloc];
}

- (void)getUserInfo
{
    QWeiboAsyncApi *api = [[QWeiboAsyncApi alloc] init];
    connection = [api getUserInfoWithConsumerKey:appKey
                                  consumerSecret:appSecret
                                  accessTokenKey:tokenKey
                               accessTokenSecret:tokenSecret
                                      resultType:RESULTTYPE_JSON
                                        delegate:self]; 
    state = QWeiboStateUserInfo;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	//读取中 
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	//读取开始
	responseData = [[NSMutableData alloc] init];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)_connection {
	//读取完成
	connection = nil;
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    id obj = [parser objectWithString:str];
    [str release];
    [parser release];
    switch (state) {
        case QWeiboStateUserInfo:
            if ([delegate respondsToSelector:@selector(QUserInfo:dic:)]) {
                [delegate QUserInfo:self dic:(NSDictionary *)obj];
            }
            break;
        case QWeiboStateUpload:
        {
            NSDictionary *dic = (NSDictionary*)obj;
            int ret = [[dic objectForKey:@"ret"] intValue];
            NSError *error = nil;
            if (ret){
                error = [NSError errorWithDomain:[dic objectForKey:@"msg"] code:ret userInfo:nil];
            }
            
            if ([delegate respondsToSelector:@selector(QUploadOver:)]) {
                [delegate QUploadOver:error];
            }
        }
        default:
            break;
    }
    
    [responseData release];
    state = QWeiboStateNone;
}

- (void)connection:(NSURLConnection *)_connection didFailWithError:(NSError *)error
{
    connection = nil;
    switch (state) {
        case QWeiboStateUpload:
            if ([delegate respondsToSelector:@selector(QUserInfo:dic:)]) {
                [delegate QUserInfo:self dic:nil];
            }
            break;
        case QWeiboStateUserInfo:
        {
            if ([delegate respondsToSelector:@selector(QUploadOver:)]) {
                [delegate QUploadOver:error];
            }
        }
        default:
            break;
    }
    
    [responseData release];
    state = QWeiboStateNone;
}

- (void)saveQAccessToken:(NSString*)email
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:self.tokenKey 
                 forKey:[NSString stringWithFormat:@"%@_%@_accessTokenKey", 
                         weiboIndentify, email]];
    [defaults setObject:self.tokenSecret 
                 forKey:[NSString stringWithFormat:@"%@_%@_accessTokenSecret", 
                         weiboIndentify, email]];
	[defaults synchronize];
}
- (void)getSourceAccessToken:(NSString*)email
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	self.tokenKey = [defaults objectForKey:[NSString stringWithFormat:@"%@_%@_accessTokenKey", 
                                            weiboIndentify, email]];
    self.tokenSecret = [defaults objectForKey:[NSString stringWithFormat:@"%@_%@_accessTokenSecret", 
                                               weiboIndentify, email]];
}

+ (void)delectThisToken:(NSString*)email
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults removeObjectForKey:[NSString stringWithFormat:@"%@_%@_accessTokenKey", 
                                            @"tencent", email]];
    [defaults removeObjectForKey:[NSString stringWithFormat:@"%@_%@_accessTokenSecret", 
                                               @"tencent", email]];
}

+ (BOOL)isExit:(NSString*)email
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	NSString *tokenKey = [defaults objectForKey:[NSString stringWithFormat:@"%@_%@_accessTokenKey", 
                                            @"tencent", email]];
    NSString *tokenSecret = [defaults objectForKey:[NSString stringWithFormat:@"%@_%@_accessTokenSecret", 
                                               @"tencent", email]];
    if (tokenKey && tokenSecret) {
        return YES;
    }else {
        return NO;
    }
}

- (void)upload:(NSString*)text image:(NSData*)data
{
    QWeiboAsyncApi *api = [[QWeiboAsyncApi alloc] init];
    connection = [api publishMsgWithConsumerKey:appKey
                    consumerSecret:appSecret
                    accessTokenKey:tokenKey
                 accessTokenSecret:tokenSecret
                           content:text 
                         imageData:data
                        resultType:RESULTTYPE_JSON
                          delegate:self];
    state = QWeiboStateUserInfo;
    [api release];
}

- (void)upload:(NSString*)text imagePath:(NSString*)path
{
    QWeiboAsyncApi *api = [[QWeiboAsyncApi alloc] init];
    connection = [api publishMsgWithConsumerKey:appKey
                                 consumerSecret:appSecret
                                 accessTokenKey:tokenKey
                              accessTokenSecret:tokenSecret
                                        content:text 
                                      imageFile:path
                                     resultType:RESULTTYPE_JSON
                                       delegate:self];
    state = QWeiboStateUserInfo;
    [api release];
}

@end
